package com.fingard.dsp.bank.directbank.cgb02;

import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingleBat;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingleBat;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingleBat;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * 广发银行单笔支付
 * 
 * @author Cruise
 * @date 2019/4/28
 */
public class CGB02SinglePay extends CGB02Base implements ISinglePay {
	public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
		RetAtsSglDetail tmpRetDetail = d_190802(p_req1908);
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	private RetAtsSglDetail d_190802(ReqSingle p_req1908) throws Exception {
		RetAtsSglDetail retDetail = new RetAtsSglDetail();
		CGB02Header bankHeader = new CGB02Header();
		bankHeader.reqSeqID = p_req1908.singleDetail.askNumber;
		if (p_req1908.singleDetail.sameBnk.equals("1")) {
			bankHeader.transCode = "0011";// 行内（同行）
		} else {
			bankHeader.transCode = "0021";// 行外（跨行）
		}

		XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
		xmlWriter.autoFormat = false;// 报文串需要整个字符串传送，中间需无回车符，否则会签名出错
		writeCommonHeader(xmlWriter, bankHeader);
		// 需要进行对账码拼接以及节点解析，采用XElement进行处理
		XElement tmpXElement = new XElement("Body", "");
		if (bankHeader.transCode.equals("0011")) {
			tmpXElement.addChild(new XElement("traceNo", p_req1908.reqHeader.transSeqID));// 网银流水号
		}
		// 定义0011和0021的公共节点
		tmpXElement.addChild(new XElement("outAccName", p_req1908.singleDetail.payName));
		tmpXElement.addChild(new XElement("outAcc", p_req1908.singleDetail.payAct));
		tmpXElement.addChild(new XElement("outAccBank", p_req1908.singleDetail.payBankName));
		tmpXElement.addChild(new XElement("inAccName", p_req1908.singleDetail.recName));
		tmpXElement.addChild(new XElement("inAcc", p_req1908.singleDetail.recAct));
		tmpXElement.addChild(new XElement("inAccBank", p_req1908.singleDetail.recBankName));
		tmpXElement.addChild(new XElement("inAccAdd", p_req1908.singleDetail.recAreaName));
		tmpXElement.addChild(new XElement("amount", p_req1908.singleDetail.payAmount));
		tmpXElement.addChild(new XElement("remark", p_req1908.singleDetail.memo));
		if (bankHeader.transCode.equals("0011")) {
			tmpXElement.addChild(new XElement("date", p_req1908.singleDetail.payDate));// 支付日期？
		}
		// 定义0011和0021的公共节点comment
		tmpXElement.addChild(new XElement("comment", p_req1908.singleDetail.abstractATS));
		if (bankHeader.transCode.equals("0011")) {
			tmpXElement.addChild(new XElement("creNo", ""));// 凭证号码
			tmpXElement.addChild(new XElement("frBalance", ""));// 转出余额
			tmpXElement.addChild(new XElement("toBalance", ""));// 转入余额
			tmpXElement.addChild(new XElement("handleFee", ""));// 手续费

		} else {
			tmpXElement.addChild(new XElement("paymentBankid", p_req1908.singleDetail.cnapsCode));// 联行号
		}
		nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
		xmlWriter.writeXElement(tmpXElement);
		xmlWriter.writeEndDocument();// 写入报文完成
		// System.out.println("dsp接收报文："+xmlWriter.toXmlString());//打印返回报文
		String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());// 发送银行
		// 测试代码
		// String[] tmpStrRet = {"",""};
		// tmpStrRet[0]="";
		// tmpStrRet[1]="<?xml version=\1.0\" encoding=\"gbk\" ?><BEDC><Message><commHead><tranCode>0011</tranCode><cifMaster>1000194103</cifMaster><entSeqNo>26082700427648</entSeqNo><tranDate>20160827</tranDate><tranTime>123717</tranTime><retCode>000</retCode><entUserId>100001</entUserId><password>5e93febf8f3df0af0d9d735e03bb25ac50bbee5b1031c23c77e2d1300a31cf01cc02d76cd8c988379892f7b8814e79f5899a18cf98f8d48ac59137b4f481ee31c1075bbd8c5449c8bb9bc6a84ed00e10ba0f641f72105f649dd3c1819f2fe3e1b77deaaa66916d0e38ead23e918d279cdf24b27fba941d59e3bbaf0934437bbefd7f9a42fdeedb263b64928a5605ea2f30f1ecbdb518cb40be9b81cfb0777e673e792c68c0b8626219881d07f0e6364aba03996cd3373ecd4c817bbbdae1518d2e8009e7aee0f7f1b2fb262f7813a417c48dc087bbe7d14e6b302838dbd389c3c04b261562e38377be0f3cd15ec47d172d75b8ce56a36fe9d0d8b42464f37eb8</password></commHead><Body><traceNo>RT2000040546681</traceNo><outAccName>UAT银企客户接入058</outAccName><outAcc>9550880200181500240</outAcc><outAccBank/><inAccName>郝蛮替</inAccName><inAcc>6214620421000001874</inAcc><inAccBank>广发银行股份有限公司</inAccBank><inAccAdd>天津市_天津市</inAccAdd><amount>10.00</amount><remark>报销</remark><date/><comment>36082700620228</comment><creNo>36082700620228</creNo><frBalance>999663.92</frBalance><toBalance/><handleFee>1.00</handleFee></Body></Message></BEDC>";
		if (tmpStrRet[0].length() == 0) {
			StringBuilder tmpSbMsg = new StringBuilder();
			// 解析银行返回
			XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
			if (tmpBkReader != null) {
				String tmpRetCode = tmpBkReader.getFirstText("/BEDC/Message/commHead/retCode");
				retDetail.respCode = "0";
				retDetail.reqSeqID = tmpBkReader.getFirstText("/BEDC/Message/commHead/entSeqNo");
				retDetail.transState = tmpRetCode;
				retDetail.payInfoCode = tmpRetCode;
			} else {
				retDetail.respCode = "-1";
				retDetail.respInfo = tmpSbMsg.toString();
			}
		} else if (tmpStrRet[0].equals(ConnState.FAIL)) {
			retDetail.respCode = "0";
			retDetail.respInfo = tmpStrRet[1];
			retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
			retDetail.transState = PaymentState.FAIL_Payment;
			retDetail.payInfoCode = tmpStrRet[0];
		} else {
			retDetail.respCode = "-1";
			retDetail.respInfo = tmpStrRet[1];
		}
		return retDetail;
	}

	// 1944 状态查询
	public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
		RetAtsSingle retAts = null;
		String queryWay = getValueAsString("queryWay");
		if ("1".equals(queryWay)) {
			retAts = newQuery(p_req1944);
		} else {
			retAts = oldQuery(p_req1944);
		}
		return retAts;
	}

	// 1944 旧版查询状态查询
	private RetAtsSingle oldQuery(ReqQrySingle p_req1944) throws Exception {
		// 返回ATS的对象
		RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);

		RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
		tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
		CGB02Header bankHeader = new CGB02Header();

		bankHeader.reqSeqID = p_req1944.reqHeader.transSeqID;
		bankHeader.transCode = "0004";
		XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
		xmlWriter.autoFormat = false;
		writeCommonHeader(xmlWriter, bankHeader);// 写入通用的头部节点
		xmlWriter.writeStartElement("Body");
		xmlWriter.writeElementString("origEntseqno", p_req1944.askNumber);
		xmlWriter.writeElementString("origEntdate", p_req1944.bgnDate.substring(0, 10).replaceAll("-", ""));
		xmlWriter.writeEndDocument();
		// System.out.println("dsp接收报文："+xmlWriter.toXmlString());//打印返回报文

		try {
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			// String[] tmpStrRet = {"",""};
			// tmpStrRet[0]="";
			// tmpStrRet[1]="<?xml version=\"1.0\" encoding=\"gbk\" ?><BEDC><Message><commHead><tranCode>0004</tranCode><cifMaster>1000001316</cifMaster><entSeqNo>201312090001104847</entSeqNo><tranDate>20131209</tranDate><tranTime>104834</tranTime><retCode>000</retCode><entUserId>100001</entUserId><password>9</password></commHead><Body><hostStatus>6</hostStatus></Body></Message></BEDC>";

			if (tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if (tmpBkReader != null) {
					String tmpRetCode = tmpBkReader.getFirstText("/BEDC/Message/commHead/retCode");
					String tmpHostStatus = tmpBkReader.getFirstText("/BEDC/Message/Body/hostStatus");
					if (tmpRetCode.equals("000") || tmpRetCode.equals("002")) {
						if (tmpBkReader.getFirstText("/BEDC/Message/commHead/entSeqNo").equals(p_req1944.reqHeader.transSeqID)) {
							tmpRetAtsDetail.respCode = "0";
						} else {
							tmpRetAtsDetail.respCode = "-1";
							tmpRetAtsDetail.respInfo = "请求REQUEST_SN与响应不相符";
						}
						tmpRetAtsDetail.transState = tmpRetCode + "+" + tmpHostStatus;
						tmpRetAtsDetail.payInfoCode = tmpRetCode;
					} else {
						tmpRetAtsDetail.respCode = "-1";
					}
					if (StringHelper.isNullOrEmpty(tmpRetAtsDetail.reqSeqID)) {
						tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
					}
				} else {
					tmpRetAtsDetail.respCode = "-1";
					tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
				}
			} else {
				tmpRetAtsDetail.respCode = "-1";
				tmpRetAtsDetail.respInfo = tmpStrRet[1];
			}
		} catch (Exception e) {
			tmpRetAtsDetail.respCode = "-1";
			tmpRetAtsDetail.respInfo = e.getMessage();
			e.printStackTrace();
		}
		retAts.writeRetDetail(tmpRetAtsDetail);
		return retAts;
	}

	// 1944 新版查询状态查询
	private RetAtsSingle newQuery(ReqQrySingle p_req1944) throws Exception {
		// 返回ATS的对象
		RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);

		RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
		tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
		CGB02Header bankHeader = new CGB02Header();
		bankHeader.reqSeqID = p_req1944.reqHeader.transSeqID;
		bankHeader.transCode = "1004";
		XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
		xmlWriter.autoFormat = false;
		writeCommonHeader(xmlWriter, bankHeader);// 写入通用的头部节点
		xmlWriter.writeStartElement("Body");
		xmlWriter.writeElementString("origEntseqno", p_req1944.askNumber);
		xmlWriter.writeElementString("origEntdate", p_req1944.bgnDate.substring(0, 10).replaceAll("-", ""));
		xmlWriter.writeEndDocument();

		try {
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			if (tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if (tmpBkReader != null) {
					String tmpRetCode = tmpBkReader.getFirstText("/BEDC/Message/commHead/retCode");
					String tmpHostStatus = tmpBkReader.getFirstText("/BEDC/Message/Body/hostStatus");
					String tmpErrorReason = tmpBkReader.getFirstText("/BEDC/Message/Body/ERRORREASON");
					if ("000".equals(tmpRetCode)) {
						if (tmpBkReader.getFirstText("/BEDC/Message/commHead/entSeqNo").equals(p_req1944.reqHeader.transSeqID)) {
							tmpRetAtsDetail.respCode = "0";
							tmpRetAtsDetail.respInfo = tmpErrorReason;
							tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
						} else {
							tmpRetAtsDetail.respCode = "-1";
							tmpRetAtsDetail.respInfo = "流水号不匹配";
						}
						// 行内汇款：
						// 6：主机交易成功
						// 7：主机交易失败
						// 8：状态未知，没有收到后台系统返回的应答
						// 跨行汇款：
						// A：支付系统正在处理
						// B：处理成功
						// C：处理失败
						// D：状态未知
						// E：大额查证
						// 9：查证取消交易
						// b:汇款失败已冲账
						tmpRetAtsDetail.transState = tmpRetCode + "+" + tmpHostStatus;
						if ("7".equals(tmpHostStatus) || "C".equals(tmpHostStatus)) {
							// 失败原因
							tmpRetAtsDetail.payInfoCode = tmpRetCode + "+" + tmpBkReader.getFirstText("/BEDC/Message/Body/ERRORREASON");
						} else {
							tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
						}
					} else {
						if ("242".equals(tmpRetCode) && !canBeNotExist(p_req1944, tmpRetAtsDetail, 30)) {
							retAts.writeRetDetail(tmpRetAtsDetail);
							return retAts;
						}
						tmpRetAtsDetail.respCode = "0";
						tmpRetAtsDetail.transState = tmpRetCode;
						tmpRetAtsDetail.payInfoCode = tmpRetCode;
					}
					if (StringHelper.isNullOrEmpty(tmpRetAtsDetail.reqSeqID)) {
						tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
					}
				} else {
					tmpRetAtsDetail.respCode = "-1";
					tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
				}
			} else {
				tmpRetAtsDetail.respCode = "-1";
				tmpRetAtsDetail.respInfo = tmpStrRet[1];
			}
		} catch (Exception e) {
			tmpRetAtsDetail.respCode = "-1";
			tmpRetAtsDetail.respInfo = e.getMessage();
			e.printStackTrace();
		}
		retAts.writeRetDetail(tmpRetAtsDetail);
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
		return null;
	}

	@Override
	public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
		return null;
	}
}
